package com.myspring.xixi.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myspring.xixi.common.dto.ChangePassDTO;
import com.myspring.xixi.common.dto.LoginDTO;
import com.myspring.xixi.common.lang.Result;
import com.myspring.xixi.domain.Business;
import com.myspring.xixi.domain.Goods;
import com.myspring.xixi.service.BusinessService;
import com.myspring.xixi.service.GoodsService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@CrossOrigin
public class ProductController {

    @Autowired
    GoodsService goodsService;

    @Autowired
    BusinessService businessService;

    /**
     * 商城首页按分页展示所有商品
     * @param currentPage
     * @return
     */
//    @RequiresAuthentication
    @GetMapping("/goods")
    public Result getProducts(@RequestParam(defaultValue = "1") Integer currentPage){
        Page page = new Page(currentPage, 12);
        IPage pageData = goodsService.page(page, new QueryWrapper<Goods>().eq("pass", 1).orderByDesc("created"));
        return Result.success(pageData);
    }

    @GetMapping("/goodsByName")
    public Result goodsByName(@RequestParam(defaultValue = "1") Integer currentPage, String search){
        Page page = new Page(currentPage, 12);
        IPage pageData = goodsService.page(page,
                new QueryWrapper<Goods>().eq("pass", 1)
                        .like("goods_name", search)
                        .orderByDesc("created"));
        return Result.success(pageData);
    }

    @GetMapping("/goodsByShop")
    public Result goodsByShop(@RequestParam(defaultValue = "1") Integer currentPage, String search){
        Business shop = businessService.getOne(new QueryWrapper<Business>().like("shop_name", search));
        Long shopId;
        if(shop != null){
            shopId = shop.getId();
        }else{
            shopId = -1L;
        }
        Page page = new Page(currentPage, 12);
        IPage pageData = goodsService.page(page,
                new QueryWrapper<Goods>().eq("pass", 1)
                        .eq("belong_id", shopId)
                        .orderByDesc("created"));
        return Result.success(pageData);
    }

    /**
     * 商家查看自己店铺中的商品
     * @param shopId
     * @return
     */
    @GetMapping("/goods/{shopId}")
    public Result getMyProducts(@PathVariable("shopId") Integer shopId){
        List<Goods> myGoods = goodsService.getMyGoods(shopId.longValue());
        if(myGoods.size() != 0){
            List<Map<String, Object>> myGoodsMap = new ArrayList<>();
            myGoods.forEach(goods -> {
                Map<String, Object> map = BeanUtil.beanToMap(goods);
                map.put("created", goods.getCreated().toLocalDate().toString());
                map.put("picGoods", "data:image/jpeg;base64,"+Base64.getEncoder().encodeToString(goods.getPicGoods()));
                myGoodsMap.add(map);
            });
            List<List<Map<String, Object>>> list = new ArrayList<>();
            String time = (String) myGoodsMap.get(0).get("created");
            int size = 0;
            int index = 0;
            for (int i = 0; i < myGoodsMap.size(); i++) {
                String created = (String) myGoodsMap.get(i).get("created");
                if(created.equals(time)){
                    size++;
                } else {
                    time = created;
                    List<Map<String, Object>> goods = myGoodsMap.subList(index, index + size);
                    list.add(goods);
                    index += size;
                    size = 1;
                }
            }
            list.add(myGoodsMap.subList(index, index + size));
            List<Map<String, Object>> listMap = new ArrayList<>();
            list.forEach(val -> {
                Map<String, Object> map = new HashMap<>();
                map.put("created", val.get(0).get("created"));
                map.put("goods", val);
                listMap.add(map);
            });
            return Result.success(listMap);
        }else{
            return Result.success(myGoods);
        }
    }

    /**
     * 商家添加商品
     * @param shopId
     * @param goods
     * @param goodsPic
     * @return
     * @throws IOException
     */
    @PostMapping("/goods/{shopId}")
    public Result addGoods(@PathVariable("shopId") Integer shopId, Goods goods, MultipartFile goodsPic) throws IOException {
        goods.setBelongId(shopId.longValue());
        goods.setPicGoods(goodsPic.getBytes());
        goods.setCreated(LocalDateTime.now());
        boolean result = goodsService.save(goods);
        return Result.success(null);
    }

    /**
     * 管理员查看所有商品
     * @param loginDTO
     * @return
     */
    @RequiresAuthentication
    @PostMapping("/goods")
    public Result allGoods(@RequestBody LoginDTO loginDTO){
        if(loginDTO.getLevel() == 1){
            List<Goods> allGoods = goodsService.getAllGoods();
            List<Map<String, Object>> goodsInfo = new ArrayList<>();
            allGoods.forEach(goods -> {
                Map<String, Object> map = BeanUtil.beanToMap(goods);
                String shopName = businessService.getShopName(goods.getBelongId());
                map.remove("belongId");
                map.put("shopName", shopName);
                map.put("created", goods.getCreated().toLocalDate());
                map.put("picGoods", "data:image/jpeg;base64," + Base64.getEncoder().encodeToString(goods.getPicGoods()));
                goodsInfo.add(map);
            });
            return Result.success(goodsInfo);
        } else {
            return Result.fail("无权查看信息！！！");
        }
    }

    /**
     * 管理员修改商品状态
     * @param changePassDTO
     * @return
     */
    @PostMapping("/goodsPass")
    public Result gPass(@RequestBody ChangePassDTO changePassDTO){
        Goods goods = goodsService.getById(changePassDTO.getId());
        if(goods.getPass() == 1){
            goods.setPass(-1);
            changePassDTO.setPass(-1);
        } else {
            goods.setPass(1);
            changePassDTO.setPass(1);
        }
        goodsService.saveOrUpdate(goods);
        return Result.success(changePassDTO);
    }

    @GetMapping("/good/{goodId}")
    public Result getGoodById(@PathVariable("goodId") Integer goodId){
        return Result.success(goodsService.getById(goodId));
    }

    @PostMapping("/changeGood")
    public Result changeGood(@RequestBody Goods goods){
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", goods.getId());
        updateWrapper.set("piece", goods.getPiece()).set("pass", goods.getPass());
        goodsService.update(updateWrapper);
        return Result.success(null);
    }
}
